package com.atguigu.tingshu.account.receiver;

import com.atguigu.tingshu.account.service.MqOpsService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import com.atguigu.tingshu.common.util.MD5;


import java.io.IOException;

/**
 * @BelongsProject: tingshu-backend
 * @BelongsPackage: com.atguigu.tingshu.account.receiver
 * @Author: coilk
 * @CreateTime: 2025-03-12  09:30
 * @Description:
 * @Version: 1.0
 */
@Slf4j
@Component
public class AccountInfoListener {
    @Autowired
    private MqOpsService mqOpsService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = MqConst.QUEUE_USER_REGISTER),
            exchange = @Exchange(value = MqConst.EXCHANGE_USER),
            key = MqConst.ROUTING_USER_REGISTER))
    // SneakyThrows可以绕开编译时候的异常 但是真正在运行期间出现异常依然会抛出来
    @SneakyThrows
    public void listenUserAccountRegister(String content, Message message, Channel channel) {
        //判断消息是否存在
        if (StringUtils.isEmpty(content)) {
            return;
        }
        //处理消息
        String msgMd5 = MD5.encrypt(content);
        //消费消息
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            //手动应答消息（将消息从队列中删除掉）
            mqOpsService.userAccountRegister(content);
            channel.basicAck(deliveryTag, false);
        } catch (GuiguException e) {
            String msgRetryKey = "msg:retry" + msgMd5;
            Long count = stringRedisTemplate.opsForValue().increment(msgRetryKey); //值自增
            //三次重试
            if (count >= 3) {
                log.error("消息已经到达了重试{}次，请人工排查错误原因：{}", count, e.getMessage());
                // 不能重试
                channel.basicNack(deliveryTag, false, false);
                stringRedisTemplate.delete(msgRetryKey);
            } else {
                log.info("消息重试{}次", count);
                channel.basicNack(deliveryTag, false, true);
            }
        } catch (Exception e) {
            log.error("签收消息时网络出现了故障，异常原因：{}", e.getMessage());
            channel.basicNack(deliveryTag, false, false);
        }


    }
}
